/*
 * util.c
 *
 *  Created on: May 6, 2009
 *      Author: gianpaolo
 */

#include "util.h"
#include <cmath>

int buscarElem(unsigned long tablero, int elem) {

	for(int i = 0; i < 9; i++) {
		if(getElem(tablero, i) == elem) {
			return i;
		}
	}
	return -1;
}

char* unrank(unsigned long rank, short int size, unsigned long fact) { //SIN IMPLEMENTAR
	return " ";
}

unsigned long fact(int n) {
	if(n == 1) return 1;
	else return n * fact(n-1);
}

short int getElem(unsigned long tablero, int fil, int col ) {
	int pos = fil*3 + col + 1;

	int temp = tablero / pow((double)10, (double)pos-1);

	return temp % 10;
}

short int getElem(unsigned long tablero, int pos) {

	int temp = tablero / pow((double)10, (double)pos);
	return temp  % 10;
}

unsigned long powU(int x, int y) {
	return (unsigned long) powl((long double)x, (long double)y);
}

/*
 * Funcion para cambiar una cifra por otra
 * @param:
 * 		tablero -> apuntador al long a modificar
 * 		x -> posicion del primer elemento (zero based)
 * 		y -> posicion del segundo elemento (zero based)
 */
void change(unsigned long *tablero, int x, int y) {
	short int valorX = getElem(*tablero, x);
	short int valorY = getElem(*tablero, y);
	unsigned long valorSum = valorY * powU(10, x);
	unsigned long valorRes = valorX * powU(10, x);

	*tablero -= valorRes;
	*tablero += valorSum;

	valorRes = valorY * powU(10,y);
	valorSum = valorX * powU(10,y);

	*tablero -= valorRes;
	*tablero += valorSum;
}
